package com.xingxuecn.limit.web.action.sys;

import com.opensymphony.xwork2.ActionSupport;
import com.xingxuecn.limit.common.model.ResultModel;
import com.xingxuecn.limit.common.model.TreeNode;
import com.xingxuecn.limit.common.utils.ResponseUtils;
import com.xingxuecn.limit.service.LimitService;
import com.xingxuecn.limit.service.impl.LimitServiceImpl;

import org.apache.struts2.ServletActionContext;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Kris at 2018/9/12 14:28
 */
public class LimitAction extends ActionSupport {
    LimitService limitService = new LimitServiceImpl();

    private Integer roleId;
    private String menuIds;
    private Boolean checked;
    private Integer userId;


    public String roleMenu() {
        String[] split = menuIds.split(",");
        Set<Integer> menuIdSet = new HashSet<>();
        for (String menuIdStr : split) {
            menuIdSet.add(Integer.valueOf(menuIdStr));
        }
        boolean isSuccess = limitService.roleMenu(roleId, menuIdSet, checked);
        ResultModel resultModel = null;
        if (isSuccess) {
            resultModel = new ResultModel(200, "授权成功");
        } else {
            resultModel = new ResultModel(500, "授权失败");
        }
        ResponseUtils.writeJson(resultModel, ServletActionContext.getResponse());
        return null;
    }

    public String loadMenuByRole() throws SQLException {
        List<TreeNode> menuList = limitService.loadMenuByRole(roleId);
        ResponseUtils.writeJson(menuList, ServletActionContext.getResponse());
        return null;
    }

    public String loadRoleByUser() throws SQLException {
        List<TreeNode> roleList = limitService.loadRoleByUser(userId);
        ResponseUtils.writeJson(roleList, ServletActionContext.getResponse());
        return null;
    }


    public String userRole() {
        ResultModel resultModel =null;
        boolean isSuccess = limitService.userRole(userId,roleId,checked);
        if(isSuccess){
            resultModel = new ResultModel(200,"授权成功");
        }else{
            resultModel = new ResultModel(500,"授权失败");
        }
        ResponseUtils.writeJson(resultModel, ServletActionContext.getResponse());
        return null;
    }


    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getMenuIds() {
        return menuIds;
    }

    public void setMenuIds(String menuIds) {
        this.menuIds = menuIds;
    }

    public Boolean getChecked() {
        return checked;
    }

    public void setChecked(Boolean checked) {
        this.checked = checked;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }
}
